<template>
  <a-drawer :title="title" :width="screenWidth" @close="cancel" :visible="visible">
    <a-form-model ref="form" class="formStyle" :model="model" :rules="validatorRules">
      <a-form-model-item label="用户账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="username">
        <a-input
          :maxLength="30"
          class="inputs"
          placeholder="请输入用户账号"
          v-model.trim="model.username"
          :readOnly="!!model.id"
        />
      </a-form-model-item>

      <template v-if="!model.id">
        <a-form-model-item label="登录密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="password">
          <a-input :maxLength="16" type="password" placeholder="请输入登录密码" v-model.trim="model.password" />
        </a-form-model-item>

        <a-form-model-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="confirmpassword">
          <a-input
            :maxLength="16"
            type="password"
            @blur="handleConfirmBlur"
            placeholder="请重新输入登录密码"
            v-model.trim="model.confirmpassword"
          />
        </a-form-model-item>
      </template>

      <a-form-model-item label="用户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="realname">
        <a-input
          :maxLength="30"
          placeholder="请输入用户名称"
          @change="handelChangeSelet"
          v-model.trim="model.realname"
        />
      </a-form-model-item>

      <a-form-model-item label="分配角色" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-select
          ref="select"
          v-model.trim="model.selectedroles"
          @change="handelChangeSelet"
          style="width: 100%"
          placeholder="请选择角色"
        >
          <a-select-option v-for="(item, index) in rolesOptions" :key="index" :value="item.id">
            {{ item.roleName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>

      <a-form-model-item
        label="分配机关"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :required="true"
        :hasFeedback="true"
        :validate-status="validateStatus"
      >
        <span slot="help">{{ validateStatus == 'error' ? '请选择上级菜单' : '&nbsp;&nbsp;' }}</span>
        <a-tree-select
          style="width: 100%"
          :treeData="treeData"
          tree-default-expand-all
          placeholder="请选择父级菜单"
          v-model="model.unitId"
          @change="handelChangeSelet"
          @blur="handleParentIdChange"
          :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
          :replaceFields="{ label: 'unitName', key: 'id', value: 'id' }"
        />
      </a-form-model-item>

      <!-- <a-form-model-item label="用户头像" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <div class="imageUpload">
          <a-upload
            accept="image/png, image/JPG,image/jpeg"
            list-type="picture-card"
            :file-list="fileList"
            :remove="remove"
            class="avatar-uploader"
            @change="picturesChange"
            :customRequest="customRequest"
            :showUploadList="showUploadList"
          >
            <div v-if="fileList.length < 1">
              <img class="pictIcon" src="@/assets/imgs/system/pict-icon.png" alt="" />
              <p class="imgText">点击上传</p>
            </div>
          </a-upload>
        </div>
      </a-form-model-item> -->
    </a-form-model>
    <div class="btn-wrap f1">
      <a-button class="ant-btn" @click="cancel">取消</a-button>
      <a-button class="ant-btn" @click="handleOk">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { uploadFile } from '@/api/api'
import { comMethods } from '@/mixins/comMethods'
import { getOneFlagTreeList, queryall, addUser, editUser, queryUserRole } from '@/api/api'
export default {
  name: 'DictItemList',
  mixins: [comMethods],
  data() {
    return {
      title: '新增',
      visible: false,
      screenWidth: 700,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      validatorRules: {
        username: [{ required: true, message: '请输入用户账号!' }, { validator: this.validateUsername }],
        password: [
          {
            required: true,
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z~!@#￥%&*.]{8,16}$/,
            message: '密码必须由8-16位数字、大小写字母组成，可有~!@#￥%&*.等特殊字符!',
          },
          { validator: this.validateToNextPassword, trigger: 'change' },
        ],
        confirmpassword: [
          { required: true, message: '请重新输入登录密码!' },
          { validator: this.compareToFirstPassword },
        ],
        realname: [{ required: true, message: '请输入用户名称!' }],
      },
      rolesOptions: [],
      treeData: [],
      validateStatus: '',
      imageUrl: [],
      fileList: [],
      showUploadList: {
        showPreviewIcon: false,
      },
    }
  },
  mounted() {
    this.loadTree()
    this.initRoleList()
  },
  methods: {
    //  ! validator begin
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
    validateToNextPassword(rule, value, callback) {
      const confirmpassword = this.model.confirmpassword
      if (value && confirmpassword && value !== confirmpassword) {
        callback('两次输入的密码不一样！')
      }
      if (value && this.confirmDirty) {
        this.$refs.form.validateField(['confirmpassword'])
      }
      callback()
    },
    compareToFirstPassword(rule, value, callback) {
      if (value && value !== this.model.password) {
        callback('两次输入的密码不一样！')
      } else {
        callback()
      }
    },
    // ! validator end

    // * get user role
    initRoleList() {
      queryall().then((res) => {
        if (res.code == 200) {
          this.rolesOptions = res.result
        }
      })
    },

    // * get tree data
    loadTree() {
      getOneFlagTreeList().then((res) => {
        if (res.code == 200) {
          this.treeData = res.result
        }
      })
    },

    // * change select suffix stutes
    handleParentIdChange(value) {
      console.log(value)
      if (!value) {
        this.validateStatus = 'error'
      } else {
        this.validateStatus = 'success'
      }
    },

    handelChangeSelet() {
      this.$forceUpdate()
    },

    picturesChange(info) {
      info.file.status = 'done'
      this.fileList = info.fileList
    },

    remove(file) {
      let uid = file.uid
      let index = this.fileList.findIndex((v) => {
        return v.uid == uid
      })
      this.imageUrl.splice(index, 1)
    },

    async customRequest(info) {
      const isJpgOrPng =
        info.file.type === 'image/jpeg' || info.file.type === 'image/png' || info.file.type === 'image/jpg'
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg，png，jpeg格式图片!')
        return
      }
      this.isLt2M = info.file.size / 1024 / 1024 < 2
      if (!this.isLt2M) {
        this.$message.warn('请上传小于200KB的照片!')
        setTimeout(() => {
          this.fileList = []
        }, 500)
        return
      }

      if (isJpgOrPng && this.isLt2M) {
        let file = info.file
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', 15)
        let res = await uploadFile(formData)
        if (res.code == 200) {
          this.imageUrl.push(res.result.halfPath)
        }
      }
    },

    add() {
      this.visible = true
      this.title = '新增'
    },

    async edit(record) {
      if (record && record.id) {
        this.model.id = record.id
        await this.getUserRoles(record.id)
        this.model.realname = record.realname
        this.model.username = record.username
        this.model.unitId = record.unitId.toString()
        if (record.avatar) {
          let obj = {
            uid: 0,
            name: 'image.png',
            status: 'done',
            url: this.imgPrefix + record.avatar,
          }
          this.fileList[0] = obj
          this.imageUrl[0] = record.avatar
        }
        this.title = '编辑'
        this.visible = true
      }
    },

    async getUserRoles(userid) {
      let { result } = await queryUserRole({ id: userid })
      this.model.selectedroles = result.length > 0 ? result[0].id : ''
    },

    async handleOk() {
      if (this.model.selectedroles == undefined) {
        this.$message.error('请选择角色')
        return
      }
      if (this.model.unitId == undefined) {
        this.$message.error('请选择机构')
        return
      }
      // if (this.fileList.length == 0) {
      //   this.$message.error('请上传用户头像')
      //   return
      // }

      // this.model.avatar = this.imageUrl[0]
      if (this.title == '新增') {
        let res = await addUser(this.model)
        this.$message.success(res.message)
        this.$emit('refresh')
        this.cancel()
      } else {
        let res = await editUser(this.model)
        this.$message.success(res.message)
        this.$emit('refresh')
        this.cancel()
      }
    },

    cancel() {
      this.model = {}
      this.imageUrl = []
      this.fileList = []
      this.visible = false
      this.validateStatus = ''
      this.$refs.form.resetFields()
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-drawer-body {
  height: calc(100% - 55px);
  display: flex;
  flex-direction: column;
}

.btn-wrap {
  display: flex;
  align-items: flex-end;
  justify-content: center;
  padding-bottom: 0.2rem;
  .ant-btn {
    border: none;
    padding: 0 0.4rem;
    &:nth-child(1) {
      margin-right: 0.5rem;
      background: #fff351;
      border: 1px solid #fff351;
      font-size: 0.14rem;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 0.2rem;
      color: #024c4e;
    }
    &:nth-child(2) {
      background: #00f8ff;
      border: 1px solid #00f8ff;
      font-size: 0.14rem;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 0.2rem;
      color: #024c4e;
    }
  }
}
</style>
